<template>
  <div id="app" :class="{isWebView}">
    <router-view></router-view>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import dbl from '@/utils/dbl'
import { getMenu } from '@/api/login'

export default {
  name: 'app',
  created () {
    this.init()
    // 修复tabs标签页打开多个页面，刷新页面后只显示一个的bug,对刷新事件进行判断
    !sessionStorage.getItem("isReload") && setTimeout(() => { sessionStorage.setItem("isReload", true) }, 100);
    window.onbeforeunload = event => { sessionStorage.removeItem("isReload") };
  },
  mounted () {
    if (this.$route.path != '/login') {
      this.menus.length ? this.checkMenu() : this.getMenu()
    }
  },
  computed: mapState({
    currentMenu: state => state.currentMenu,
    user: state => state.user.user,
    menus: state => state.user.menus,
    isWebView: state => state.isWebView
  }),
  watch: {
    '$route.path' (val) {
      this.checkMenu()
    }
  },
  methods: {
    init () {
      let path = this.$route.path
      let token = dbl.get('token')
      if (!token && (path !== '/' || path !== '/login')) {
        this.$router.push('/login')
      }
      if (token) {
        this.$store.dispatch('init')
        this.$store.dispatch('initUser')
      }
    },
    getMenu () {
      dbl.get('token') && getMenu().then(res => {
        const list = res.data.data
        dbl.set("menus", list);
        this.$store.commit("SET_MENU", list);
        this.checkMenu()
      })
    },
    checkMenu () {
      let path = this.$route.path === '/' ? '/index' : this.$route.path;
      let disabled = false
      const setCurrentMenu = (item, _path) => {
        if (path.indexOf(_path) > -1) {
          item.link = _path
          !disabled && this.$store.commit('changeCurrentMenu', item)
          disabled = true
        }
      }
      this.menus.forEach(item => {
        item.link = path
        setCurrentMenu(item, item.path);
        !disabled && item.children && item.children.forEach(child => {
          setCurrentMenu(item, child.path)
          !disabled && child.children && child.children.forEach(sub => {
            setCurrentMenu(item, child.path + sub.path)
          })
        })
      })
    },

  }
}
</script>

<style lang="scss">
#app.isWebView .layout-content-wrapp {
  display: block;
  width: 100%;
}
.systemMessage {
  .el-message__icon {
    font-size: 36px;
  }
  .el-message__content {
    font-size: 30px;
  }
}
</style>
